#include "widget.h"
#include "ui_widget.h"
#include "sendfile.h"

#include <QFileDialog>
#include <QMessageBox>
#include <QThread>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
    ,thread(new QThread)
    ,sendFile(new SendFile)
{
    ui->setupUi(this);

    sendFile->moveToThread(thread);


    connect(this,&Widget::sendDisconnectServer,sendFile,&SendFile::disConnectServer);
    connect(sendFile,&SendFile::recvMessage,this,[=](const QString &message){
        ui->textEditRecv->append(message);
    });

    // 发送文件
    connect(this, &Widget::sendFileEmit, sendFile, &SendFile::send);
    // 发送消息
    connect(this, &Widget::sendMessageEmit, sendFile, &SendFile::sendMessageSlot);

    connect(this, &Widget::startConnect, sendFile, &SendFile::connectServer);
    // 这个信号是由 QTcpSocket::connected 发出的
    connect(sendFile,&SendFile::connectOK,this,[=](){
        QMessageBox::information(this,"连接服务器","链接服务器成功");
    });

    connect(sendFile,&SendFile::gameover,this,[=](){
        /*thread->quit();
        thread->wait();
        thread->deleteLater();
        thread=nullptr;*/
        QMessageBox::information(this,"断开服务器","断开服务器成功");
    });

    connect(sendFile,&SendFile::currentValue,ui->progressBar,&QProgressBar::setValue);
    thread->start();
    qDebug()<<"0current ThreadID"<<QThread::currentThread();
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_sendFile_clicked()
{
    emit sendFileEmit(ui->filePath->text());
}


void Widget::on_connectServerPtn_clicked()
{
    if (!thread) {
        thread = new QThread;
    }
    if (!thread->isRunning()) {
        thread->start();
    }
    unsigned short port = ui->port->text().toShort();
    QString ip = ui->ip->text().toUtf8();
   
    emit startConnect(port,ip);

}


void Widget::on_selFile_clicked()
{
    QString path = QFileDialog::getOpenFileName();
    if(path.isEmpty())
    {
        QMessageBox::warning(this,"选择文件","选择的文件不能为空");
        return;
    }
    ui->filePath->setText(path);
}


void Widget::on_buttonSend_clicked()
{
    emit sendMessageEmit(ui->textEditSend->toPlainText());
    //ui->textEditSend->clear();
}


void Widget::on_buttonDisconnect_clicked()
{
    emit sendDisconnectServer();
}

